package com.wsh.crawler.scheduler;

import com.wsh.crawler.constant.NewsSourceEnum;
import com.wsh.crawler.service.CrawlerService;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class NewsCrawlerTask {

    private final static Logger LOGGER = LoggerFactory.getLogger(NewsCrawlerTask.class);

    @Resource
    private CrawlerService crawlerService;


    @Scheduled(fixedRate = 30 * 60 * 1000L)
    public void crawlNewsTask() {
        long start = System.currentTimeMillis();
        try {
            doCrawlBatch();
            LOGGER.info("定时爬取任务完成, cost={}ms", System.currentTimeMillis() - start);
        } catch (Throwable t) { // 注意是 Throwable
            LOGGER.error("定时爬取任务出现致命错误，将继续保活调度线程", t);
        }
    }


    private void doCrawlBatch() {
        LOGGER.info("开始分批次爬取任务...");
        for (NewsSourceEnum source : NewsSourceEnum.values()) {
            if (source == NewsSourceEnum.SERIE_A) {
                LOGGER.info("暂不执行 {}", source.name());
                continue;
            }
            if (source == NewsSourceEnum.PREMIER_LEAGUE) {
                LOGGER.info("暂不执行 {}", source.name());
                continue;
            }
            if (source == NewsSourceEnum.LA_LIGA) {
                LOGGER.info("暂不执行 {}", source.name());
                continue;
            }
            if (source == NewsSourceEnum.BUNDESLIGA) {
                LOGGER.info("暂不执行 {}", source.name());
                continue;
            }
            if (source == NewsSourceEnum.LIGUE_1) {
                LOGGER.info("暂不执行 {}", source.name());
                continue;
            }
            try {
                LOGGER.info("爬取数据源: {}", source.name());
                crawlerService.crawlNews(source);
            } catch (Exception e) {
                LOGGER.error("数据源 {} 爬取失败: {}", source, e, e);
            }
        }
    }

}
